#!/usr/bin/env bash
#filename: merge_image.sh

#set -x

SCRIPT_NAME=$(basename "$0")
SCRIPT_DIR=$(cd "$(dirname "$0")";pwd)
CUR_DIR=$(pwd)

BIRDGE_ROOTFS_DIR="${CUR_DIR}/squashfs-root-birdge"

BIRDGE_VMLINUX_FILE="${CUR_DIR}/vmlinux/acu100-birdge-vmlinux.bin"

REMK_DIR_SCRIPT="${CUR_DIR}/remk_dir.sh"
REMK_IMAGE_SCRIPT="${CUR_DIR}/remk_image.sh"

MERGE_DIR="${CUR_DIR}/merge"
MERGE_ROOTFS_FILE="output_new_rootfs.bin"
MERGE_IMAGE_FILE="output_new_image.bin"

MERGE_BIRDGE_ROOTFS_FILE="acu100-birdge-rootfs.bin"

MERGE_BIRDGE_IMAGE_FILE="acu100-birdge-image.bin"


if [ -d "${BIRDGE_ROOTFS_DIR}" -a -f "${BIRDGE_VMLINUX_FILE}" -a -f "${REMK_DIR_SCRIPT}" -a -x "${REMK_DIR_SCRIPT}" -a -f "${REMK_IMAGE_SCRIPT}" -a -x "${REMK_IMAGE_SCRIPT}" ]; then
	echo "Merge image ${MERGE_DIR}/${MERGE_BIRDGE_IMAGE_FILE} ..."
	[ -d "${MERGE_DIR}" ] || mkdir "${MERGE_DIR}"
	[ -f "${MERGE_DIR}/${MERGE_ROOTFS_FILE}" ] && rm "${MERGE_DIR}/${MERGE_ROOTFS_FILE}"
	[ -f "${MERGE_DIR}/${MERGE_IMAGE_FILE}" ] && rm "${MERGE_DIR}/${MERGE_IMAGE_FILE}"
	[ -f "${MERGE_DIR}/${MERGE_BIRDGE_ROOTFS_FILE}" ] && rm "${MERGE_DIR}/${MERGE_BIRDGE_ROOTFS_FILE}"
	[ -f "${MERGE_DIR}/${MERGE_BIRDGE_IMAGE_FILE}" ] && rm "${MERGE_DIR}/${MERGE_BIRDGE_IMAGE_FILE}"
	( cd "${BIRDGE_ROOTFS_DIR}"; ${REMK_DIR_SCRIPT} )
	sleep 3
	${REMK_IMAGE_SCRIPT} -z -s "${BIRDGE_ROOTFS_DIR}" -o "${MERGE_DIR}"
	[ -f "${MERGE_DIR}/${MERGE_ROOTFS_FILE}" ] && mv "${MERGE_DIR}/${MERGE_ROOTFS_FILE}" "${MERGE_DIR}/${MERGE_BIRDGE_ROOTFS_FILE}"
	${REMK_IMAGE_SCRIPT} -c -k "${BIRDGE_VMLINUX_FILE}" -r "${MERGE_DIR}/${MERGE_BIRDGE_ROOTFS_FILE}" -o "${MERGE_DIR}"
	[ -f "${MERGE_DIR}/${MERGE_IMAGE_FILE}" ] && mv "${MERGE_DIR}/${MERGE_IMAGE_FILE}" "${MERGE_DIR}/${MERGE_BIRDGE_IMAGE_FILE}"
	echo "Merge image ${MERGE_DIR}/${MERGE_BIRDGE_IMAGE_FILE} done."
fi

exit 0

